package com.foreverwin.jzymes.framework.quartz.util;

import com.foreverwin.jzymes.framework.quartz.domain.SysJob;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 执行定时任务
 * 
 * @author ruoyi
 *
 */
public class ScheduleRunnable implements Runnable
{
    private static final Logger log = LoggerFactory.getLogger(ScheduleRunnable.class);

    private Object target;
    private Method method;
    private SysJob params;
    private Exception exception;

    public ScheduleRunnable(String beanName, String methodName, SysJob job)
            throws NoSuchMethodException, SecurityException
    {
        this.target = SpringContextUtil.getBean(beanName);
        this.params = job;

        if (params != null)
        {
            this.method = target.getClass().getDeclaredMethod(methodName, SysJob.class);
        }
        else
        {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }

    @Override
    public void run()
    {
        try
        {
            ReflectionUtils.makeAccessible(method);
            if ( params != null )
            {
                method.invoke(target, params);
            }
            else
            {
                method.invoke(target);
            }
        } catch (InvocationTargetException e) {
            exception = new Exception( e.getTargetException() );
        } catch (Exception e){
            log.error("执行定时任务  - ：", e);
            exception = e;
        }
    }

    public void throwException() throws Exception {
        if( exception != null ){
            throw exception;
        }
    }
}
